<script setup lang="ts">
import { ref, computed, onUnmounted, watch, nextTick } from "vue";
import { formatTimestamp } from "../utils/time";

// 定义轨迹数据接口
interface TrackItem {
  course: number;
  gtime: number;
  stime: number;
  speed: number;
  mileage: number;
  lon: number;
  lat: number;
  [key: string]: any;
}

// 定义组件Props
type Props = {
  list: TrackItem[];
  type?: number; // 1.中交慧联 2.中交兴路
};
const props = defineProps<Props>();

// 表格引用
const xTable = ref();
// 定时器
const timer = ref<number | null>(null);
// 默认列配置
const defaultColumns = ref([
  {
    field: "course",
    title: "车辆方向"
  },
  {
    field: "gtime",
    title: "定位时间"
  },
  {
    field: "stime",
    title: "系统时间"
  },
  {
    field: "speed",
    title: "行驶速度"
  },
  {
    field: "mileage",
    title: "当前里程"
  },
  {
    field: "lon",
    title: "经度"
  },
  {
    field: "lat",
    title: "纬度"
  }
]);

// 动态列配置
const DynamicColumns = computed(() => {
  // 复制默认列配置
  let columns = [...defaultColumns.value];

  // 如果是类型2，过滤掉系统时间列
  if (props.type === 2) {
    columns = columns.filter(item => item.field !== "stime");
  }

  return columns;
});

// 时间格式化方法
const formatTime = (timestamp: number) => {
  return formatTimestamp(timestamp);
};

const init = async () => {
  await xTable.value?.reloadData(props.list);
  reset();
};

// 开始滚动
const currentIndex = ref(0);
const start = (radio: number) => {
  if (!props.list.length || !xTable.value) return;
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }

  // 因为progress进度条有一个定时延迟，所以这里需要延迟1秒才开始滚动
  timer.value = window.setInterval(() => {
    if (currentIndex.value >= props.list.length) {
      stop();
      return;
    }
    xTable.value.scrollToRow(props.list[currentIndex.value]);
    xTable.value.setCurrentRow(props.list[currentIndex.value]);
    currentIndex.value++;
  }, 1000 / radio);
};

// 暂停滚动
const pause = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

// 停止滚动-适用于计时器到期
const stop = () => {
  currentIndex.value = 0;
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

// 重置滚动
const reset = () => {
  currentIndex.value = 0;
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  if (xTable.value && props.list.length) {
    nextTick(() => {
      xTable.value.scrollToRow(props.list[0]);
      xTable.value.setCurrentRow(props.list[0]);
    });
  }
};

// 监听列表数据变化
watch(
  () => props.list,
  newVal => {
    if (!newVal.length) {
      reset();
    }
  },
  { deep: true }
);

// 组件卸载时清理定时器
onUnmounted(() => {
  reset();
});

// 暴露方法给父组件
defineExpose({ start, pause, stop, reset, init });
</script>

<template>
  <div>
    <!-- vxe-table表格组件 -->
    <vxe-table
      border
      ref="xTable"
      show-overflow="tooltip"
      :column-config="{ resizable: true }"
      :virtual-y-config="{ enabled: true, gt: 0 }"
      :row-config="{ isCurrent: true, isHover: true }"
      height="250"
      :data="list"
      auto-resize
      empty-text="暂无数据"
    >
      <!-- 序号列 -->
      <vxe-table-column type="seq" title="序号" width="100"></vxe-table-column>
      <!-- 动态生成的数据列 -->
      <vxe-table-column v-for="item in DynamicColumns" :key="item.field" :field="item.field" :title="item.title">
        <template #default="{ row }">
          <span v-if="item.field === 'gtime' || item.field === 'stime'">
            {{ formatTime(row[item.field]) }}
          </span>
          <span v-else-if="item.field === 'speed'">
            {{ row[item.field] || row[item.field] == 0 ? row[item.field] : "-" }}
            km/h
          </span>
          <span v-else-if="item.field === 'mileage'">
            {{ row[item.field] || row[item.field] == 0 ? row[item.field] : "-" }}
            km
          </span>
          <span v-else-if="item.field === 'lon' || item.field === 'lat'">
            {{ row[item.field] || row[item.field] == 0 ? (row[item.field] / 600000).toFixed(7) : "-" }}
          </span>
          <span v-else>
            {{ row[item.field] || row[item.field] == 0 ? row[item.field] : "-" }}
          </span>
        </template>
      </vxe-table-column>
    </vxe-table>
  </div>
</template>

<style lang="scss" scoped>
:deep(.vxe-table) {
  border-collapse: collapse;
}
:deep(.vxe-table--body-wrapper) {
  height: calc(250px - 40px) !important;
}
:deep(.vxe-table--header-wrapper) {
  background-color: #f9f9f9;
}
:deep(.vxe-table--current-row) {
  background-color: #f5f7fa !important;
}
:deep(.vxe-cell) {
  padding: 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
